#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <vector>
#include "LockGuard.hpp"

#define NUM 4

int ticket = 1000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; // 定义成全局变量

class pthreadDate
{
public:
    pthreadDate(int number/*, pthread_mutex_t *lock*/)
    {
        pthreadname = "Thread" + std::to_string(number);
        //_lock = lock;
    }

public:
    std::string pthreadname;
    //pthread_mutex_t *_lock;
};

void *buyTickets(void *args)
{
    pthreadDate *td = static_cast<pthreadDate *>(args);
    while (1)
    {
        // pthread_mutex_lock(td->_lock); // 加锁
        // pthread_mutex_lock(&lock);
        {
            LockGuard Lock(&lock);
            if (ticket > 0)
            {
                usleep(1000);
                std::cout << "pid : " << getpid() << "tid :  " << pthread_self() << td->pthreadname << " ticket : " << ticket << std::endl;
                ticket--;
                // pthread_mutex_unlock(td->_lock); // 解锁
                // pthread_mutex_unlock(&lock);
            }
            else
            {
                // pthread_mutex_unlock(td->_lock); // 解锁
                // pthread_mutex_unlock(&lock);
                break;
            }
        }
        usleep(1000); // 模拟抢完票之后的处理动作
    }
}

int main()
{
    // pthread_mutex_t lock;
    // pthread_mutex_init(&lock, nullptr);

    pthread_t tid;
    std::vector<pthread_t> tids;
    std::vector<pthreadDate *> tds;

    for (int i = 1; i <= NUM; i++)
    {
        pthreadDate *td = new pthreadDate(i/*, &lock*/);
        tds.push_back(td);
        pthread_create(&tid, nullptr, buyTickets, td);
        tids.push_back(tid);
    }

    for (int i = 0; i < tids.size(); i++)
    {
        pthread_join(tid, nullptr);
    }
    for (int i = 0; i < tds.size(); i++)
    {
        delete tds[i];
    }

    // pthread_mutex_destroy(&lock);

    return 0;
}